/**
 * fileName: InitMsgCode.java
 *     Date: 2012-5-27
 **/
package com.stranger.common.util;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.springframework.core.io.Resource;

import com.stranger.common.bean.MessageCode;

/**
 * @作者 stranger.lin
 *
 * @时间 2012-5-27
 */
public class InitMsgCode {

	private Resource[] locations;
	private Map<String,MessageCode> messages=new HashMap<String, MessageCode>();
	public void init(){
		System.err.println("初始化消息码.....");
		try {
			for (Resource resource : locations) {
				messages.putAll(this.parseXML(resource.getInputStream()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	/**
	 * 解析消息码
	 * */
	@SuppressWarnings("unchecked")
	private Map<String, MessageCode> parseXML(InputStream stream){
		Map<String, MessageCode> resultMap=new HashMap<String, MessageCode>();
		try {
			SAXBuilder sax=new SAXBuilder();
			Document doc=sax.build(stream);
			Element root=doc.getRootElement();
			List<Element> list=root.getChildren();
			for (Element element : list) {
				MessageCode message=new MessageCode();
				message.setCode(element.getAttributeValue("code"));
				message.setModelName(element.getAttributeValue("modelname"));
				message.setMsg(element.getTextTrim());
				message.setType(element.getAttributeValue("type"));
				if (resultMap.containsKey(element.getAttributeValue("code"))) {
					System.err.println("在"+element.getAttributeValue("modelname")+"里有重复的code,请认真检查");
					resultMap.remove(element.getAttributeValue("code"));
					
				}
				resultMap.put(element.getAttributeValue("code"), message);
			} 
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return resultMap;
	}
	
	
	public Resource[] getLocations() {
		return locations;
	}
	public void setLocations(Resource[] locations) {
		this.locations = locations;
	}


	public Map<String, MessageCode> getMessages() {
		return messages;
	}
	
	
}
